package com.bsj.sipgateway.util;

import lombok.extern.slf4j.Slf4j;

import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAccessor;
import java.util.Locale;

/**    
 * @Description:时间工具类，主要处理ISO 8601格式转换
 * @author bsj-chenjunkang
 * @date 2022/8/24
 */
@Slf4j
public class DateUtil {

	private static final DateTimeFormatter yyyy_MM_dd_T_HH_mm_ss_SSSXXX = DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss");
    private static final DateTimeFormatter yyyy_MM_dd_HH_mm_ss = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
    private static final DateTimeFormatter yyMMddHHmmss = DateTimeFormatter.ofPattern("yyMMddHHmmss");
    
	public static String yyyy_MM_dd_HH_mm_ssToISO8601(String formatTime) {
        try {
            return LocalDateTime.parse(formatTime, yyyy_MM_dd_HH_mm_ss).format(yyyy_MM_dd_T_HH_mm_ss_SSSXXX);
        } catch (Exception e) {
            log.error("日期{}转换yyyy-MM-dd'T'HH:mm:ss格式失败", formatTime);
        }
        return "";
    }

    public static String yyMMddHHmmssToISO8601(String formatTime){
        try {
            return LocalDateTime.parse(formatTime, yyMMddHHmmss).format(yyyy_MM_dd_T_HH_mm_ss_SSSXXX);
        } catch (Exception e) {
            log.error("日期{}转换yyyy-MM-dd'T'HH:mm:ss格式失败", formatTime);
        }
        return "";
    }
	
	public static String ISO8601Toyyyy_MM_dd_HH_mm_ss(String formatTime) {
        try {
            return LocalDateTime.parse(formatTime, yyyy_MM_dd_T_HH_mm_ss_SSSXXX).format(yyyy_MM_dd_HH_mm_ss);
        } catch (Exception e) {
            log.error("日期{}转换yyyy_MM_dd_HH_mm_ss格式失败", formatTime);
        }
        return "";
    }

    public static long ISO8601ToTimestamp(String formatTime) {
        try {
            return  LocalDateTime.parse(formatTime, yyyy_MM_dd_T_HH_mm_ss_SSSXXX).atZone(ZoneId.systemDefault()).toInstant().toEpochMilli();
        } catch (Exception e) {
            log.error("日期{}转换时间戳（毫秒）失败", formatTime);
        }
        return 0;
    }
	
	public static long yyyy_MM_dd_HH_mm_ssToTimestamp(String formatTime) {
        try {
            return  LocalDateTime.parse(formatTime, yyyy_MM_dd_HH_mm_ss).atZone(ZoneId.systemDefault()).toEpochSecond();
        } catch (Exception e) {
            log.error("日期{}转换时间戳（秒）失败", formatTime);
        }
        return 0;
	}

    /**
     * 获取当前时间
     *
     * @return
     */
    public static String getNow() {
        LocalDateTime nowDateTime = LocalDateTime.now();
        return yyyy_MM_dd_HH_mm_ss.format(nowDateTime);
    }

}
